package com.testapp.bluetoothtest08;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.testapp.bluetoothtest08.Constant.Constants;
import com.testapp.bluetoothtest08.File.Cipher;
import com.testapp.bluetoothtest08.Http.OkHttp;
import com.testapp.bluetoothtest08.cipher.UserCipherService;
import com.testapp.bluetoothtest08.cipher.entity.JoinCheckStr;
import com.testapp.bluetoothtest08.cipher.entity.UserJoin;
import com.testapp.bluetoothtest08.cipher.entity.user.UserPrivateData;
import com.testapp.bluetoothtest08.cipher.entity.user.UserPrivateDataStr;
import com.testapp.bluetoothtest08.cipher.impl.UserCipherServiceImpl;
import com.testapp.bluetoothtest08.pojo.User;


import java.util.List;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    private Button register_ok, Return;
    private EditText register_username, register_password, register_name, register_id, register_iphone;
    private String username, password, name, id, phone;
    private UserJoin userJoin;
    private UserPrivateData userPrivateData;
    private User user;
    private UserCipherService userCipherService = new UserCipherServiceImpl();

    JSONObject obj = new JSONObject();
    OkHttp http = new OkHttp();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        init();
    }

    private void init() {
        register_ok = findViewById(R.id.register_ok);
        Return = findViewById(R.id.to_MainActivity);
        register_ok.setOnClickListener(this);
        Return.setOnClickListener(this);

        register_username = findViewById(R.id.register_username);
        register_password = findViewById(R.id.register_password);
        register_name = findViewById(R.id.register_name);
        register_id = findViewById(R.id.register_id);
        register_iphone = findViewById(R.id.register_iphone);
    }

    @Override
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.register_ok:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        getData();
                        try {
                            //将 实体类 变为Json
                            String userStr = JSON.toJSONString(user);
                            System.out.println("发送的数据：---> "+ userStr);
                            //发送数据注册
                            String result = http.httpPost(Constants.REGISTER_URL, userStr);
                            System.out.println("服务器返回的结果 ----> " + result);
                            //code：0 ，msg：ok，data：{token，joinCheckStr}，time：xxx
                            JSONObject jo = JSONObject.parseObject(result);

                            if(jo!=null){
                                String data = jo.getString("data");
                                System.out.println("服务器的data ----> " + data);
                                //{token，joinCheckStr}
                                JSONObject ja = JSONObject.parseObject(data);
                                if (ja != null) {
                                    System.out.println(ja.toJSONString());
                                    //获取临时 token
                                    Constants.token = ja.getString("token");
                                    System.out.println("token --> " + Constants.token);
                                    //获取返回值 joinCheckStr:a,y,t2
                                    String a = ja.getString("a");
                                    String y = ja.getString("y");
                                    String t2 = ja.getString("t2");
                                    System.out.println("joinCheckStr ---> " + "a:" + a + "y:" + y + "t2:" + t2);
                                    JoinCheckStr joinCheckStr = new JoinCheckStr();
                                    joinCheckStr.a=a;
                                    joinCheckStr.y=y;
                                    joinCheckStr.t2=t2;
                                    if (a != null && y != null && t2 != null) {
                                        // 根据 返回值joinCheckStr 计算userPrivateDataStr
                                        UserPrivateDataStr userPrivateDataStr = userCipherService.UserJoinResponse(userPrivateData, joinCheckStr);
                                        String key = JSONObject.toJSONString(userPrivateDataStr);
                                        System.out.println("key ---- > "+key);
                                        new Cipher().write(key);
                                        System.out.println("Cipher --- >" + new Cipher().read());
                                        //返回OK
                                        // ---------------------- 作弊 ---------------
//                                        String zuobi = "{\"a\":\"252343675788361504772280818824690321641701846601221603762420640291605906459995\",\"c\":\"871150770870580837425903444924\",\"p\":\"1746856145997762929285190925031575852766588676798700695333540\",\"secList\":[\"871150770870580837425903444924\",\"1070112537255731684785\",\"1152913760569457945690\",\"1650391937913881051919656581060900368401866529973480541780082\",\"2115720880121307617158\",\"819\",\"802\",\"706\",\"726120022303187809265\"],\"t2\":\"1045608342865575932373\",\"y\":\"1645504557321206042154969182557350504982735156513387973351218649\"}";
//                                        new Cipher().write(zuobi);
//                                        System.out.println("new --- >"+new Cipher().read());
                                        // ---------------------- 作弊 ---------------
                                        String ok = JSONObject.toJSONString(true);
                                        String re = http.httpPostWithToken(Constants.REGISTER_OK_URL,ok);
                                        System.out.println("服务器 ----> " + re);
                                        success();
                                    }
                                } else {
                                    failed();
                                }
                            }else{
                                failed();
                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                            failed();
                        } finally {
                            //清除临时token
                            Constants.token = "";
                        }
                    }
                }).start();
                break;
            case R.id.to_MainActivity:
                intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                break;
        }
    }

    public void success() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                register_username.setText("");
                register_password.setText("");
                register_name.setText("");
                register_id.setText("");
                register_iphone.setText("");
                Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(RegisterActivity.this, MainActivity.class));
            }
        });
    }

    public void getData() {
        //用户输入
        username = register_username.getText().toString();
        password = register_password.getText().toString();
        name = register_name.getText().toString();
        id = register_id.getText().toString();
        phone = register_iphone.getText().toString();
        //本地生成密钥
        List<Object> list = userCipherService.UserJoinRequest(null, null);
        userJoin = (UserJoin) list.get(0);
        userPrivateData = (UserPrivateData) list.get(1);
        //生成实体类
        user = new User(name, username, password, id, phone, userJoin.y, userJoin.s, userJoin.c, userJoin.PKu);
    }

    public void failed() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(RegisterActivity.this, "注册失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
}